//
//  CircleQueue.swift
//  Swift-LeetCode
//
//  Created by 卢悦明 on 2024/1/26.
//

import UIKit
/// 循环队列(暂时没有处理动态扩容的问题)
class CircleQueue<Q: Equatable>: NSObject {
    var elements: [Q] = [Q]()
    var headQ = 0
    var size: Int = 0
    let defaultValue: Q
    init(_ size: Int = 10, defaultValue: Q) {
        self.size = 0
        self.defaultValue = defaultValue
        elements = [Q](repeating: defaultValue, count: size)
        super.init()
    }
//   队列长度
    func count() -> Int {
        self.size
    }
//  队列是否为空
    func isEmpty() -> Bool {
        self.size == 0
    }
//    入队列
    func push(elem: Q) {
        let index = index(size)
        elements[index] = elem
        size += 1
    }
//    出队列
    @discardableResult func pop() -> Q? {
        if  isEmpty() {
            return nil
        } else {
            let value = elements[headQ]
            elements[headQ] = defaultValue
            headQ = index(1)
            size -= 1
            if size == 0 {
                headQ = 0
            }
            return value
        }
    }
//    队列头部元素
    func peek() -> Q? {
        size == 0 ? nil : elements[headQ]
    }
}
extension CircleQueue {
    private func index(_ index: Int) -> Int {
        (index + headQ) % elements.count
    }
    /// 打印栈中的内容<从栈顶到尾部>
    func printQueue() {
        let elements = self.elements
        print("队列结构")
        var printStr = "头部 "
        var top = "————"
        for (index,elem) in elements.enumerated() {
            if index == headQ {
                printStr = printStr + "$\(elem)$ "
            } else {
                printStr = printStr + "\(elem) "
            }
            top = top + "——"
        }
        top = top + "————"
        printStr = printStr + "尾部"
        print(top)
        print(printStr)
        print(top)
    }
}

